<template>
    <div>
        交互式 Choropleth 地图
        <div id="myMap" class="map-box"></div>
    </div>
</template>

<script>
import L from 'leaflet'
import Provider from '@/components/chinatmsproviders'
require('leaflet/dist/leaflet.css')
import geoJson from '@/components/geojson/shandong'

export default {
    data() {
        return {
            mapKey: '', //你的key
            cityData: [
                {

                    "name": "济南市",
                    "value": 500,
                    "wrwname": "二氧化碳",
                    "num": 1200
                }, {
                    "name": "青岛市",
                    "value": 400,
                    "wrwname": "硫化铁",
                    "num": 12
                },
                {
                    "name": "泰安市",
                    "value": 300,
                    "wrwname": "氩钾钙",
                    "num": 389
                },
                {
                    "name": "日照市",
                    "value": 200,
                    "wrwname": "铅",
                    "num": 12
                },
                {
                    "name": "济南市",
                    "value": 100,
                    "wrwname": "铅",
                    "num": 12
                },



            ],
            geoJsonT: null,
            infoL: null,
        }
    },
    mounted() {
        Provider(L) // 挂载插件
        this.getMap()
    },
    methods: {

        /**获取两个颜色中的相对应颜色 */
        getColor(d) {
            return this.getContinuationColorByVal(0, 600, "#cee2f7", "#08306b", d)
        },

        getContinuationColorByVal(minVal, maxVal, firstColor, secondColor, val) {
            let ratio = (val - minVal) / (maxVal - minVal);
            let fArr = this.hex2RgbArr(firstColor);
            let sArr = this.hex2RgbArr(secondColor);
            let color = [];
            for (let i = 0; i < fArr.length; i++) {
                let c = Math.round(fArr[i] + (sArr[i] - fArr[i]) * ratio);
                color.push(c);
            }
            return this.rgbArr2Hex(color);
        },
        hex2RgbArr(hex) {
            // 16进制颜色值的正则
            var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
            // 把颜色值变成小写
            var color = hex.toLowerCase();
            if (reg.test(color)) {
                // 如果只有三位的值，需变成六位，如：#fff => #ffffff
                if (color.length === 4) {
                    var colorNew = '#';
                    for (var i = 1; i < 4; i += 1) {
                        colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
                    }
                    color = colorNew;
                }
                // 处理六位的颜色值，转为RGB
                var colorChange = [];
                for (var i = 1; i < 7; i += 2) {
                    colorChange.push(parseInt('0x' + color.slice(i, i + 2)));
                }
                return colorChange;
            }
        },
        rgbArr2Hex(rgbArr) {
            let strHex = '#';
            // 转成16进制
            for (var i = 0; i < rgbArr.length; i++) {
                let hex = Number(rgbArr[i]).toString(16);
                hex = hex.length == 1 ? '0' + hex : hex;
                strHex += hex;
            }
            return strHex;
        },

        style(feature) {
            //循环cityData 获取value
            var cityName = feature.properties.name;
            var d = 0;
            for (var i = 0; i < this.cityData.length; i++) {
                if (cityName == this.cityData[i].name) {
                    d = this.cityData[i].value;
                }
            }
            return {
                fillColor: this.getColor(d),
                weight: 2,
                opacity: 1,
                color: 'white',
                dashArray: '3',
                fillOpacity: 0.7
            };
        },

        zoomToFeature(e) {
            map.fitBounds(e.target.getBounds());
        },
        highlightFeature(e) {
            var layer = e.target;

            layer.setStyle({
                weight: 5,
                color: '#666',
                dashArray: '',
                fillOpacity: 0.7
            });


            console.log("layer", layer);
            layer.bringToFront();

            var cityName = layer.feature.properties.name;
            var d;
            for (var i = 0; i < this.cityData.length; i++) {
                if (cityName == this.cityData[i].name) {
                    d = this.cityData[i];
                }
            }
            this.infoL.update(d);

        },
        resetHighlight(e) {
            console.log("移除");
            this.geoJsonT.resetStyle(e.target);
            this.infoL.update();
        },
        /**  */
        onEachFeature(feature, layer) {
            console.log("layer", layer);
            layer.bindTooltip(feature.properties.name, {
                permanent: true,  // 永久显示（而不是悬停时显示）
                direction: 'center',  // 文字居中
                className: 'city-label'  // 自定义 CSS 类
            });

            layer.on({
                mouseover: this.highlightFeature,
                mouseout: this.resetHighlight,
                click: this.zoomToFeature
            });
        },
        getMap() {
            let myCenter = new L.LatLng(36.675807, 117.000923)
            let map = L.map('myMap', {
                center: myCenter,
                zoom: 8
            })
            L.tileLayer.chinaProvider('TianDiTu.Normal.Map', { maxZoom: 18, minZoom: 5, key: this.mapKey }).addTo(map);
            L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', { maxZoom: 18, minZoom: 5, key: this.mapKey }).addTo(map);
            this.geoJsonT = L.geoJson(geoJson, {
                style: (feature) => this.style(feature),
                onEachFeature: (feature, layer) => this.onEachFeature(feature, layer)
            }).addTo(map)

            this.infoL = L.control();

            this.infoL.onAdd = function (map) {
                this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
                this.update();
                return this._div;
            };

            // method that we will use to update the control based on feature properties passed
            this.infoL.update = function (props) {
                console.log("props", props);

                if (props) {
                    this._div.innerHTML = '<h4>US Population Density</h4>' + (props.name ?
                        '<b>' + props.wrwname + '</b><br />' + props.num + ' people / mi<sup>2</sup>'
                        : 'Hover over a state');
                } else {
                    this._div.innerHTML = '<h4>US Population Density</h4>' + 'Hover over a state';
                }


            };

            this.infoL.addTo(map);



            //图例
            var legend = L.control({ position: 'bottomright' });

            legend.onAdd = function (map) {

                var div = L.DomUtil.create('div', 'info legend'),
                    grades = [0, 10, 20, 50, 100, 200, 500, 1000],
                    labels = [];

                // loop through our density intervals and generate a label with a colored square for each interval
                for (var i = 0; i < grades.length; i++) {
                    // div.innerHTML +=
                    //     '<i style="background:' + this.getColor(grades[i] + 1) + '"></i> ' +
                    //     grades[i] + (grades[i + 1] ? '&ndash;' + grades[i + 1] + '<br>' : '+');
                }

                return div;
            };

            legend.addTo(map);


        }
    }
}
</script>
<style>
.info {
    padding: 6px 8px;
    font: 14px/16px Arial, Helvetica, sans-serif;
    background: white;
    background: rgba(255, 255, 255, 0.8);
    box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
    border-radius: 5px;
}

.info h4 {
    margin: 0 0 5px;
    color: #777;
}


.legend {
    width: 40px;
    height: 300px;
    background: linear-gradient(to top, #cee2f7, #08306b);
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>
